// 应用主类
class HttpRequestTool {
    constructor() {
        this.currentTab = 1;
        this.tabs = new Map();
        this.settings = {};
        this.urlHistory = [];
        this.init();
        this.loadAllPersistent(); // 启动时自动恢复
    }

    async init() {
        try {
            // 显示启动画面（主题已在HTML中预加载）
            this.showSplashScreen();

            // 初始化设置对象
            this.initializeSettings();

            // 初始化基本功能
            this.initEventListeners();
            this.initTabs();
            this.urlHistory = [];

            // 设置初始面板状态
            this.updateToolbarVisibility('http');
            document.body.setAttribute('data-current-panel', 'http');

            // 隐藏启动画面 - 确保至少显示1秒
            setTimeout(() => {
                this.hideSplashScreen();
                // 在界面显示后再加载其他数据
                setTimeout(() => {
                    this.loadSettings().then(() => {
                        this.loadUrlHistory();
                    });
                }, 500);
            }, 1000);
        } catch (error) {
            console.error('应用初始化失败:', error);
            // 强制显示界面
            this.hideSplashScreen();
        }
    }

    showSplashScreen() {
        document.getElementById('splash-screen').style.display = 'flex';
        document.getElementById('main-app').style.display = 'none';
    }

    hideSplashScreen() {
        document.getElementById('splash-screen').style.display = 'none';
        document.getElementById('main-app').style.display = 'flex';
    }

    // 在启动画面显示前加载主题设置
    async loadThemeBeforeSplash() {
        try {
            // 从localStorage加载保存的主题设置
            const savedTheme = localStorage.getItem('hermes-theme');
            console.log('加载保存的主题:', savedTheme);

            if (savedTheme && (savedTheme === 'light' || savedTheme === 'warm')) {
                document.documentElement.setAttribute('data-theme', savedTheme);
                this.settings = { theme: savedTheme };
                console.log('应用主题:', savedTheme);

                // 确保主题选择器显示正确的值
                setTimeout(() => {
                    const themeSelect = document.getElementById('settings-theme');
                    if (themeSelect) {
                        themeSelect.value = savedTheme;
                    }
                }, 100);
            } else {
                // 默认主题
                this.settings = { theme: 'light' };
                document.documentElement.setAttribute('data-theme', 'light');
                console.log('使用默认主题: light');
            }
        } catch (error) {
            console.error('加载主题设置失败:', error);
            // 使用默认主题
            this.settings = { theme: 'light' };
            document.documentElement.setAttribute('data-theme', 'light');
        }
    }

    // 初始化设置对象
    initializeSettings() {
        try {
            // 从localStorage读取保存的主题，而不是从DOM属性读取
            const savedTheme = localStorage.getItem('hermes-theme') || 'light';
            this.settings = { theme: savedTheme };

            // 确保DOM和主题选择器都显示正确的值
            document.documentElement.setAttribute('data-theme', savedTheme);
            setTimeout(() => {
                const themeSelect = document.getElementById('settings-theme');
                if (themeSelect) {
                    themeSelect.value = savedTheme;
                }
            }, 100);

            console.log('初始化设置完成，当前主题:', savedTheme);
        } catch (error) {
            console.error('初始化设置失败:', error);
            this.settings = { theme: 'light' };
            document.documentElement.setAttribute('data-theme', 'light');
        }
    }

    // 切换主题
    changeTheme(theme) {
        try {
            if (theme === 'light' || theme === 'warm') {
                document.documentElement.setAttribute('data-theme', theme);
                this.settings.theme = theme;
                localStorage.setItem('hermes-theme', theme);
                const themeSelect = document.getElementById('settings-theme');
                if (themeSelect) themeSelect.value = theme;
                this.saveAllPersistent();
            }
        } catch (error) {
            console.error('切换主题失败:', error);
        }
    }

    initEventListeners() {
        try {
            // 工具栏事件
            const toggleSidebar = document.getElementById('toggle-sidebar');
            if (toggleSidebar) toggleSidebar.addEventListener('click', () => this.toggleSidebar());

            const newTab = document.getElementById('new-tab');
            if (newTab) newTab.addEventListener('click', () => this.createNewTab());

            const saveTab = document.getElementById('save-tab');
            if (saveTab) saveTab.addEventListener('click', () => this.saveCurrentTab());

            const loadTab = document.getElementById('load-tab');
            if (loadTab) loadTab.addEventListener('click', () => this.showLoadTabDialog());

            const urlHistory = document.getElementById('url-history');
            if (urlHistory) urlHistory.addEventListener('click', () => this.showUrlHistoryDialog());

            // 侧边栏导航
            document.querySelectorAll('.nav-item').forEach(item => {
                item.addEventListener('click', () => this.switchPanel(item.dataset.tab));
            });

            // HTTP请求相关
            const sendBtn = document.getElementById('send-btn');
            if (sendBtn) sendBtn.addEventListener('click', () => this.sendRequest());

            const addHeader = document.getElementById('add-header');
            if (addHeader) addHeader.addEventListener('click', () => this.addHeaderRow());

            const addParam = document.getElementById('add-param');
            if (addParam) addParam.addEventListener('click', () => this.addParamRow());

            // 选项卡切换
            document.querySelectorAll('.option-tab').forEach(tab => {
                tab.addEventListener('click', () => this.switchOptionTab(tab.dataset.option));
            });

            // 响应选项卡切换
            document.querySelectorAll('.response-tab').forEach(tab => {
                tab.addEventListener('click', () => this.switchResponseTab(tab.dataset.response));
            });

            // SM4加密测试
            const testEncrypt = document.getElementById('test-encrypt');
            if (testEncrypt) testEncrypt.addEventListener('click', () => this.testEncrypt());

            const testDecrypt = document.getElementById('test-decrypt');
            if (testDecrypt) testDecrypt.addEventListener('click', () => this.testDecrypt());

            const copyResult = document.getElementById('copy-result');
            if (copyResult) copyResult.addEventListener('click', () => this.copyResult());

            const clearContent = document.getElementById('clear-content');
            if (clearContent) clearContent.addEventListener('click', () => this.clearContent());

            // 密钥配置折叠/展开
            const keyConfigToggle = document.getElementById('key-config-toggle');
            if (keyConfigToggle) keyConfigToggle.addEventListener('click', () => this.toggleKeyConfig());

            // 签名配置相关
            const openSignatureConfig = document.getElementById('open-signature-config');
            if (openSignatureConfig) openSignatureConfig.addEventListener('click', () => this.openSignatureConfig());

            const defaultSignatureKey = document.getElementById('default-signature-key');
            if (defaultSignatureKey) defaultSignatureKey.addEventListener('input', () => this.updateSignatureStatus());

            // 自定义签名配置切换
            const useCustomSignature = document.getElementById('use-custom-signature');
            if (useCustomSignature) useCustomSignature.addEventListener('change', () => this.toggleCustomSignatureConfig());

            // 签名密钥输入监听
            const signatureKey = document.getElementById('signature-key');
            if (signatureKey) signatureKey.addEventListener('input', () => this.updateSignatureStatus());

            // 设置相关
            const settingsTheme = document.getElementById('settings-theme');
            if (settingsTheme) settingsTheme.addEventListener('change', (e) => this.changeTheme(e.target.value));

            const exportSettings = document.getElementById('export-settings');
            if (exportSettings) exportSettings.addEventListener('click', () => this.exportSettings());

            const importSettings = document.getElementById('import-settings');
            if (importSettings) importSettings.addEventListener('click', () => this.importSettings());

            const clearHistory = document.getElementById('clear-history');
            if (clearHistory) clearHistory.addEventListener('click', () => this.clearHistory());

            // 模态框
            const modalOverlay = document.getElementById('modal-overlay');
            if (modalOverlay) {
                modalOverlay.addEventListener('click', (e) => {
                    if (e.target.id === 'modal-overlay') this.hideModal();
                });
            }

            const modalClose = document.querySelector('.modal-close');
            if (modalClose) modalClose.addEventListener('click', () => this.hideModal());

            const modalCancel = document.getElementById('modal-cancel');
            if (modalCancel) modalCancel.addEventListener('click', () => this.hideModal());

            // URL输入自动完成和标签页名称更新
            const urlInput = document.getElementById('url-input');
            if (urlInput) {
                urlInput.addEventListener('input', (e) => {
                    this.updateUrlSuggestions(e.target.value);
                    this.updateCurrentTabName(e.target.value);
                    this.updateParamsFromUrl();
                });
                
                // 动态调整文本框高度的函数
                function adjustTextareaHeight(textarea) {
                    // 重置高度以获取准确的scrollHeight
                    textarea.style.height = '36px';
                    const scrollHeight = textarea.scrollHeight;
                    const lineHeight = 20; // 行高
                    const padding = 16; // 上下内边距总和
                    const minHeight = 36; // 最小高度（单行）
                    const maxHeight = 200; // 最大高度限制
                    
                    // 计算实际需要的高度
                    let newHeight = Math.max(minHeight, Math.min(scrollHeight, maxHeight));
                    textarea.style.height = newHeight + 'px';
                }

                // 添加焦点和失焦事件处理
                urlInput.addEventListener('focus', () => {
                    adjustTextareaHeight(urlInput);
                });
                
                urlInput.addEventListener('input', () => {
                    if (document.activeElement === urlInput) {
                        adjustTextareaHeight(urlInput);
                    }
                });
                
                urlInput.addEventListener('blur', () => {
                    urlInput.style.height = '36px';
                });
            }

            // JSON编辑器增强
            // this.initJsonEditor(); // 将在ui.js中初始化

            // 键盘快捷键
            // document.addEventListener('keydown', (e) => this.handleKeyboardShortcuts(e)); // 将在ui.js中初始化

            // 监听SM4全局key/iv变更自动保存
            const sm4KeyInput = document.getElementById('sm4-shared-key');
            if (sm4KeyInput) {
                sm4KeyInput.addEventListener('change', () => this.saveAllPersistent());
                sm4KeyInput.addEventListener('blur', () => this.saveAllPersistent());
            }
            const sm4IVInput = document.getElementById('sm4-shared-iv');
            if (sm4IVInput) {
                sm4IVInput.addEventListener('change', () => this.saveAllPersistent());
                sm4IVInput.addEventListener('blur', () => this.saveAllPersistent());
            }

            // 恢复sidebar折叠状态
            const sidebar = document.getElementById('sidebar');
            if (sidebar) {
                const collapsed = localStorage.getItem('hermes-sidebar-collapsed');
                if (collapsed === '1') {
                    sidebar.classList.add('collapsed');
                } else {
                    sidebar.classList.remove('collapsed');
                }
            }
        } catch (error) {
            console.error('初始化事件监听器失败:', error);
        }
    }

    initTabs() {
        // 生成唯一ID
        const uniqueId = this.generateUniqueId();
        this.tabs.set(1, {
            id: 1,
            uniqueId: uniqueId,
            name: '未命名',
            method: 'GET',
            url: '',
            // 使用多环境参数存储结构
            environments: {}, // key是环境名称，value是包含headers, params, body等的对象
            headers: {}, // 保持兼容性，但将在未来版本中移除
            body: '', // 保持兼容性，但将在未来版本中移除
            options: this.getDefaultOptions()
        });
        // updateTabsDisplay() 将在tabs.js初始化后调用
    }

    // 生成唯一ID
    generateUniqueId() {
        return 'tab_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }

    getDefaultOptions() {
        return {
            addTimestamp: false,
            timestampField: 'timestamp',
            timestampPos: 'query',
            timestampUnit: 'milliseconds',  // 新增：默认为毫秒
            addNonce: false,
            nonceField: 'nonce',
            noncePos: 'query',
            nonceLength: 16,
            addAppId: false,
            appIdField: 'appId',
            appIdPos: 'query',
            appIdValue: '',
            addSignature: false,
            signatureField: 'signature',
            signaturePos: 'query',
            signatureKey: '',
            useCustomSignature: false,
            customSignatureCode: '',
            encryptBody: false,
            decryptResponse: false,
            sm4Key: '',
            sm4IV: ''
        };
    }

    // 从URL提取域名作为标签页名称
    extractTabNameFromUrl(url) {
        if (!url || url.trim() === '') {
            return '未命名';
        }

        try {
            const urlObj = new URL(url);
            let hostname = urlObj.hostname;

            // 移除www前缀
            if (hostname.startsWith('www.')) {
                hostname = hostname.substring(4);
            }

            return hostname;
        } catch (error) {
            // 如果URL解析失败，返回未命名
            return '未命名';
        }
    }

    toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        sidebar.classList.toggle('collapsed');
        // 持久化折叠状态
        if (sidebar.classList.contains('collapsed')) {
            localStorage.setItem('hermes-sidebar-collapsed', '1');
        } else {
            localStorage.setItem('hermes-sidebar-collapsed', '0');
        }
    }

    switchPanel(panelName) {
        console.log('切换到面板:', panelName); // 调试信息

        // 设置body的data-current-panel属性，用于CSS选择器
        document.body.setAttribute('data-current-panel', panelName);

        // 更新导航状态
        document.querySelectorAll('.nav-item').forEach(item => {
            item.classList.remove('active');
        });
        document.querySelector(`[data-tab="${panelName}"]`).classList.add('active');

        // 切换面板
        document.querySelectorAll('.panel').forEach(panel => {
            panel.classList.remove('active');
            console.log('移除active类:', panel.id); // 调试信息
        });

        const targetPanel = document.getElementById(`${panelName}-panel`);
        if (targetPanel) {
            targetPanel.classList.add('active');
            console.log('添加active类:', targetPanel.id); // 调试信息
        } else {
            console.error('找不到面板:', `${panelName}-panel`);
        }

        // 控制工具栏按钮的显示/隐藏
        this.updateToolbarVisibility(panelName);

        // 当切换到HTTP面板时，刷新环境选择框
        if (panelName === 'http' && window.environmentSelector) {
            console.log('刷新环境选择框');
            window.environmentSelector.updateEnvironmentSelector();
        }
        
        // 当切换到全局参数面板时，渲染全局请求头UI
        if (panelName === 'global-params' && window.renderGlobalHeadersPanel) {
            console.log('渲染全局请求头面板');
            window.renderGlobalHeadersPanel();
        }
    }

    updateToolbarVisibility(panelName) {
        const httpRelatedButtons = [
            document.getElementById('new-tab'),
            document.getElementById('save-tab'),
            document.getElementById('load-tab'),
            document.getElementById('url-history')
        ];

        if (panelName === 'http') {
            // HTTP面板：显示所有HTTP相关按钮
            httpRelatedButtons.forEach(btn => {
                if (btn) btn.style.display = 'inline-flex';
            });
        } else {
            // 其他面板：隐藏HTTP相关按钮
            httpRelatedButtons.forEach(btn => {
                if (btn) btn.style.display = 'none';
            });
        }
    }

    switchOptionTab(optionName) {
        document.querySelectorAll('.option-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelector(`[data-option="${optionName}"]`).classList.add('active');

        document.querySelectorAll('.option-panel').forEach(panel => {
            panel.classList.remove('active');
        });
        document.getElementById(`${optionName}-panel`).classList.add('active');
    }

    switchResponseTab(responseName) {
        document.querySelectorAll('.response-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelector(`[data-response="${responseName}"]`).classList.add('active');

        document.querySelectorAll('.response-panel').forEach(panel => {
            panel.classList.remove('active');
        });
        document.getElementById(`response-${responseName}`).classList.add('active');
    }

    // 开始重命名标签页
    startRenameTab(tabId, titleElement) {
        const tab = this.tabs.get(tabId);
        if (!tab) return;

        // 创建输入框
        const input = document.createElement('input');
        input.type = 'text';
        input.className = 'tab-title-input';
        input.value = tab.name;
        input.style.cssText = `
            background: var(--bg-color);
            border: 1px solid var(--primary-color);
            border-radius: 3px;
            padding: 2px 6px;
            font-size: 13px;
            width: 100px;
            min-width: 60px;
            max-width: 150px;
        `;

        // 替换标题元素
        titleElement.style.display = 'none';
        titleElement.parentNode.insertBefore(input, titleElement);

        // 选中输入框内容
        input.focus();
        input.select();

        // 完成重命名的函数
        const finishRename = () => {
            const newName = input.value.trim();
            if (newName && newName !== tab.name) {
                tab.name = newName;
                this.updateTabsDisplay();
                this.showMessage('标签页已重命名');
            } else {
                // 如果没有更改或输入为空，恢复原来的显示
                titleElement.style.display = '';
                input.remove();
            }
        };

        // 取消重命名的函数
        const cancelRename = () => {
            titleElement.style.display = '';
            input.remove();
        };

        // 绑定事件
        input.addEventListener('blur', finishRename);
        input.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                finishRename();
            } else if (e.key === 'Escape') {
                e.preventDefault();
                cancelRename();
            }
        });

        // 阻止点击事件冒泡
        input.addEventListener('click', (e) => {
            e.stopPropagation();
        });
    }

    // 显示标签页右键菜单
    showTabContextMenu(event, tabId) {
        // 移除已存在的菜单
        this.hideTabContextMenu();

        const menu = document.createElement('div');
        menu.className = 'tab-context-menu';
        menu.style.cssText = `
            position: fixed;
            top: ${event.clientY}px;
            left: ${event.clientX}px;
            background: var(--bg-color);
            border: 1px solid var(--border-color);
            border-radius: 4px;
            box-shadow: var(--shadow-lg);
            z-index: 10000;
            min-width: 120px;
            padding: 4px 0;
        `;

        const menuItems = [
            {
                text: '复制标签页',
                icon: '📋',
                action: () => {
                    this.hideTabContextMenu();
                    this.duplicateTab(tabId);
                }
            },
            {
                text: '重命名',
                icon: '✏️',
                action: () => {
                    this.hideTabContextMenu();
                    const tabElement = document.querySelector(`[data-tab-id="${tabId}"]`);
                    const titleElement = tabElement.querySelector('.tab-title');
                    this.startRenameTab(tabId, titleElement);
                }
            },
            {
                text: '关闭标签',
                icon: '✕',
                action: () => {
                    this.hideTabContextMenu();
                    this.closeTab(tabId);
                },
                disabled: this.tabs.size <= 1
            },
            {
                text: '关闭其他标签',
                icon: '⊗',
                action: () => {
                    this.hideTabContextMenu();
                    this.closeOtherTabs(tabId);
                },
                disabled: this.tabs.size <= 1
            },
            {
                text: '关闭全部标签',
                icon: '⊠',
                action: () => {
                    this.hideTabContextMenu();
                    this.closeAllTabs();
                },
                disabled: this.tabs.size <= 1
            }
        ];

        menuItems.forEach(item => {
            const menuItem = document.createElement('div');
            menuItem.className = `tab-context-menu-item ${item.disabled ? 'disabled' : ''}`;
            menuItem.innerHTML = `
                <span class="menu-icon">${item.icon}</span>
                <span class="menu-text">${item.text}</span>
            `;

            if (!item.disabled) {
                menuItem.addEventListener('click', item.action);
            }

            menu.appendChild(menuItem);
        });

        document.body.appendChild(menu);

        // 点击其他地方关闭菜单
        setTimeout(() => {
            document.addEventListener('click', this.hideTabContextMenu.bind(this), { once: true });
        }, 0);

        // 调整菜单位置，确保不超出屏幕
        const rect = menu.getBoundingClientRect();
        if (rect.right > window.innerWidth) {
            menu.style.left = (event.clientX - rect.width) + 'px';
        }
        if (rect.bottom > window.innerHeight) {
            menu.style.top = (event.clientY - rect.height) + 'px';
        }
    }

    // 隐藏标签页右键菜单
    hideTabContextMenu() {
        const existingMenu = document.querySelector('.tab-context-menu');
        if (existingMenu) {
            existingMenu.remove();
        }
    }

    // 关闭其他标签页
    closeOtherTabs(keepTabId) {
        if (this.tabs.size <= 1) return;

        const tabsToClose = [];
        this.tabs.forEach((tab, id) => {
            if (id !== keepTabId) {
                tabsToClose.push(id);
            }
        });

        tabsToClose.forEach(id => {
            this.tabs.delete(id);
        });

        this.currentTab = keepTabId;
        this.updateTabsDisplay();
        const tab = this.tabs.get(this.currentTab);
        this.loadTabData(tab);

        this.showMessage(`已关闭其他 ${tabsToClose.length} 个标签页`);
    }

    // 关闭全部标签页
    closeAllTabs() {
        if (this.tabs.size <= 1) return;

        const closedCount = this.tabs.size - 1;

        // 保留第一个标签页，关闭其他所有标签页
        const firstTabId = this.tabs.keys().next().value;
        const tabsToClose = [];

        this.tabs.forEach((tab, id) => {
            if (id !== firstTabId) {
                tabsToClose.push(id);
            }
        });

        tabsToClose.forEach(id => {
            this.tabs.delete(id);
        });

        // 重置第一个标签页为默认状态
        const firstTab = this.tabs.get(firstTabId);
        firstTab.name = '未命名';
        firstTab.method = 'GET';
        firstTab.url = '';
        firstTab.headers = {};
        firstTab.body = '';
        firstTab.options = this.getDefaultOptions();

        this.currentTab = firstTabId;
        this.updateTabsDisplay();
        this.loadTabData(firstTab);

        this.showMessage(`已关闭 ${closedCount} 个标签页`);
    }

    // 自动持久化关键配置和标签页
    async saveAllPersistent() {
        // 收集所有标签页数据，确保多环境配置正确保存
        const tabsArr = [];
        this.tabs.forEach(tab => {
            // 创建标签页的深拷贝以确保数据独立性
            const tabCopy = {
                id: tab.id,
                uniqueId: tab.uniqueId,
                name: tab.name,
                method: tab.method,
                url: tab.url,
                // 确保保存所有环境的独立配置
                environments: tab.environments || {},
                // 保持向后兼容性
                headers: tab.headers || {},
                body: tab.body || '',
                options: tab.options || this.getDefaultOptions()
            };
            tabsArr.push(tabCopy);
        });
        // 收集SM4配置
        const sm4Key = document.getElementById('sm4-shared-key')?.value || '';
        const sm4IV = document.getElementById('sm4-shared-iv')?.value || '';
        // 收集主题
        const theme = this.settings.theme || (document.documentElement.getAttribute('data-theme') || 'light');
        // 组装持久化对象
        const persistent = {
            defaultSignatureKey: this.settings.defaultSignatureKey || '',
            defaultCustomSignatureCode: this.settings.defaultCustomSignatureCode || '',
            sm4Key,
            sm4IV,
            theme,
            globalHeaders: this.settings.globalHeaders || [], // 保存全局参数
            tabs: tabsArr,
            currentTab: this.currentTab // 保存当前选中的标签页ID
        };
        await fetch('/api/settings', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(persistent)
        });
    }

    async loadAllPersistent() {
        try {
            const res = await fetch('/api/settings');
            if (!res.ok) return;
            const data = await res.json();
            // 恢复主题
            if (data.theme) {
                this.settings.theme = data.theme;
                document.documentElement.setAttribute('data-theme', data.theme);
                const themeSelect = document.getElementById('settings-theme');
                if (themeSelect) themeSelect.value = data.theme;
            }
            // 恢复签名配置
            if (data.defaultSignatureKey !== undefined) {
                this.settings.defaultSignatureKey = data.defaultSignatureKey;
                document.getElementById('default-signature-key').value = data.defaultSignatureKey;
            }
            if (data.defaultCustomSignatureCode !== undefined) {
                this.settings.defaultCustomSignatureCode = data.defaultCustomSignatureCode;
                document.getElementById('custom-signature-code').value = data.defaultCustomSignatureCode;
            }
            // 恢复全局请求头
            if (data.globalHeaders !== undefined && Array.isArray(data.globalHeaders)) {
                this.settings.globalHeaders = data.globalHeaders;
            } else {
                this.settings.globalHeaders = [];
            }
            // 恢复SM4配置
            let globalSm4Key = '';
            let globalSm4IV = '';
            if (data.sm4Key !== undefined) {
                globalSm4Key = data.sm4Key;
                document.getElementById('sm4-shared-key').value = data.sm4Key;
            }
            if (data.sm4IV !== undefined) {
                globalSm4IV = data.sm4IV;
                document.getElementById('sm4-shared-iv').value = data.sm4IV;
            }
            // 恢复标签页
            if (Array.isArray(data.tabs) && data.tabs.length > 0) {
                this.tabs.clear();
                
                // 首先获取所有已保存标签页的列表，用于恢复filename和group信息
                let savedTabsList = [];
                try {
                    const listResponse = await fetch('/api/tabs/list');
                    if (listResponse.ok) {
                        const listData = await listResponse.json();
                        if (Array.isArray(listData)) {
                            savedTabsList = listData;
                        }
                    }
                } catch (err) {
                    console.warn('获取已保存标签页列表失败，无法恢复标签页分组信息:', err);
                }
                
                data.tabs.forEach(tab => {
                    // 同步全局sm4Key/sm4IV到每个标签页的options
                    if (!tab.options) tab.options = {};
                    if (globalSm4Key) tab.options.sm4Key = globalSm4Key;
                    if (globalSm4IV) tab.options.sm4IV = globalSm4IV;
                    
                    // 确保environments对象存在，用于多环境配置
                    if (!tab.environments) {
                        tab.environments = {};
                    }
                    
                    // 深拷贝标签页数据以避免引用问题
                    const clonedTab = JSON.parse(JSON.stringify(tab));
                    
                    // 尝试根据URL和名称匹配已保存的标签页，恢复filename和group信息
                    // 这里使用简化的匹配逻辑：先尝试通过name匹配，再尝试通过URL匹配
                    const matchedSavedTab = savedTabsList.find(savedTab => {
                        // 优先通过唯一标识符或精确名称匹配
                        return savedTab.name === clonedTab.name && 
                               (savedTab.url === clonedTab.url || 
                                (!savedTab.url && !clonedTab.url)); // 处理空URL情况
                    });
                    
                    // 如果找到匹配的已保存标签页，恢复filename和group
                    if (matchedSavedTab && matchedSavedTab.filename) {
                        clonedTab.filename = matchedSavedTab.filename;
                        clonedTab.group = matchedSavedTab.group;
                    }
                    
                    this.tabs.set(tab.id, clonedTab);
                });
                
                // 恢复当前选中的标签页ID，如果保存的currentTab存在且有效，则使用它
                let targetTabId = data.tabs[0].id; // 默认选择第一个标签页
                if (data.currentTab !== undefined && this.tabs.has(data.currentTab)) {
                    targetTabId = data.currentTab;
                }
                
                this.currentTab = targetTabId;
                this.updateTabsDisplay(); // 先更新显示，确保选中状态正确
                this.loadTabData(this.tabs.get(targetTabId)); // 然后加载数据
            }
        } catch (e) {
            // 忽略
        }
    }
}

// 导出类以便在其他文件中使用
window.HttpRequestTool = HttpRequestTool;